import { App } from 'vue'
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import store from '@/store'
import { useUserStore } from '@/store/modules/user'
import { notification } from 'ant-design-vue'
import { ACCESS_TOKEN } from '@/store/store-types'
import qs from 'qs'

// 扩展 AxiosRequestConfig 接口
interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
  formData?: boolean
  concatenate?: boolean
  // 自定义请求头
  headers?: Record<string, string>
}

const userStore = useUserStore(store)

// 创建 axios 实例
const request: any = axios.create({
  // API 请求的默认前缀 
  timeout: 6000, // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error: any) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = sessionStorage.getItem(ACCESS_TOKEN)
    const status = error.response.status

    if (status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message,
      })
    }

    if (status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed',
      })
      if (token) {
        userStore.Logout().then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use((config: ExtendedAxiosRequestConfig) => {
  const token = sessionStorage.getItem(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers = config.headers || {}
    config.headers['x-cf-random'] = token
  }

  // 处理 formData 配置
  if (config.formData) {
    config.headers = config.headers || {}
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
    if (config.data) {
      config.data = qs.stringify(config.data)
    }
  }

  // 将参数拼接到url后面
  if (config.concatenate && config.params) {
    const queryString = qs.stringify(config.params, { arrayFormat: 'brackets' })
    config.url = config.url + '?' + queryString
    config.params = {}
  }

  // 处理GET请求参数编码
  if (config.method === 'get' && config.params) {
    // 使用qs.stringify对params进行编码，并设置arrayFormat为'brackets'以支持数组参数
    const queryString = qs.stringify(config.params, { arrayFormat: 'brackets' })
    // 将编码后的查询字符串添加到URL
    config.url = `${config.url}${config.url?.includes('?') ? '&' : '?'}${queryString}`
    // 清空params以避免axios重复处理
    config.params = {}
  }

  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  // eslint-disable-next-line no-unused-vars
  installed: false,
  install(app: App, request: AxiosInstance) {
    if (this.installed) {
      return
    }
    this.installed = true

    if (!request) {
      // eslint-disable-next-line no-console
      console.error('You have to install axios')
      return
    }

    app.config.globalProperties['axios'] = request
    app['axios'] = {
      get: () => {
        return request
      },
    }
    app.config.globalProperties['$http'] = request
    app['$http'] = {
      get: () => {
        return request
      },
    }
  },
}

export const VueAxios = {
  vm: {},
  install(app: App) {
    app.use(installer, request)
  },
}

export default request

